package com.xianggu.spring.aop.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 手写AOP核心实现（基于JDK动态代理）
 */
public class SimpleAOP {

    //======================= 1. 定义Advice接口 =======================
    public interface Advice {
        void before(Method method, Object[] args);
        void after(Method method, Object result);
    }

    //======================= 2. 实现具体Advice =======================
    static class LogAdvice implements Advice {
        @Override
        public void before(Method method, Object[] args) {
            System.out.println("[Log] 调用方法: " + method.getName());
            System.out.println("[Log] 参数: " + java.util.Arrays.toString(args));
        }

        @Override
        public void after(Method method, Object result) {
            System.out.println("[Log] 方法返回: " + result);
        }
    }

    //======================= 3. 创建代理工厂 =======================
    public static Object createProxy(Object target, Advice advice) {
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        // 前置增强
                        advice.before(method, args);
                        
                        // 执行原始方法
                        Object result = method.invoke(target, args);
                        
                        // 后置增强
                        advice.after(method, result);
                        return result;
                    }
                });
    }

    //======================= 4. 测试用例 =======================
    interface UserService {
        String getUserById(int id);
    }

    static class UserServiceImpl implements UserService {
        @Override
        public String getUserById(int id) {
            return "User-" + id;
        }
    }

    public static void main(String[] args) {
        // 原始对象
        UserService target = new UserServiceImpl();
        
        // 创建代理对象（织入日志增强）
        UserService proxy = (UserService) createProxy(target, new LogAdvice());
        
        // 调用代理方法
        String result = proxy.getUserById(1001);
        System.out.println("最终结果: " + result);
    }
}